package cachemanager;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.PersistenceConfiguration;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy;

/**
 * Created by luoqifei on 2016/9/14.
 */
public class EhCache {
    CacheManager cacheManager;
    private int priNum = 10;
    public String defaultConf = "src/main/resources/ehcache.xml";
    public EhCache(){
        //CacheManager supports two creation modes: singleton and instance.create by static method 'create
        // is singleton modes'
        this.cacheManager = CacheManager.create();

    }
    private int getPriNum(){
        return this.priNum;
    }
    public EhCache(String fileSrc){
        this.cacheManager = CacheManager.create(defaultConf);
    }
    public void closeEhCache(){
        this.cacheManager.shutdown();
    }
    public void addCache(Cache cacheName) {
        this.cacheManager.addCache(cacheName);
    }
public static void main(String args[]){
    EhCache ehCacheManager = new EhCache();
    //A Cache is a thread-safe logical representation of a set of data elements
    Cache cache = ehCacheManager.cacheManager.getCache("topologies");

    //add some element in cache
    Element element = new Element("key1","values");
    cache.put(element);

    Element result = cache.get("key1");

System.out.println("cache value:"+result.getObjectValue().toString());


    //Create a singleton CacheManager using defaults
    CacheManager manager = CacheManager.create();
    //Create a Cache specifying its configuration.
    Cache testCache = new Cache(
            new CacheConfiguration("testCache", 20) // name and maxEntriesLocalHeap
                    .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU)
                    .eternal(false)
                    .timeToLiveSeconds(20)
                    .timeToIdleSeconds(10)
                    .diskExpiryThreadIntervalSeconds(0)
                    .persistence(new PersistenceConfiguration().strategy(PersistenceConfiguration.Strategy.LOCALTEMPSWAP)));
    manager.addCache(testCache);

    Element element1 = new Element("ky2","value2");
    testCache.put(element1);
    for(int i=0;i<70;i++){
        System.out.println((i+1)+":"+testCache.get("ky2").getObjectValue().toString());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
}
